package cn.jit.ssm.demo;

import cn.jit.ssm.beans.domain.Book;
import cn.jit.ssm.utils.HttpClientUtil;
import com.alibaba.druid.util.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 调用豆瓣的API的Demo
 * @author: Cecurio
 * @create: 2017-12-13 15:20
 **/
public class Demo3 {
    public static void test() {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "https://api.douban.com/v2/book/isbn/978-7-302-22798-4";
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1000).setConnectionRequestTimeout(1000)
            .setSocketTimeout(1000).setRedirectsEnabled(true).build();
        httpGet.setConfig(requestConfig);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("---------");
            System.out.println(statusCode);
            HttpEntity entity = httpResponse.getEntity();
            System.out.println("ContentEncoding: " + entity.getContentEncoding());
            System.out.println("ContentLength: " + entity.getContentLength());
            System.out.println("ContentType: " + entity.getContentType());
            System.out.println("Content: " + entity.getContent());
            System.out.println("isChunked: " + entity.isChunked());
            System.out.println("isRepeatable: " + entity.isRepeatable());
            System.out.println("isStreaming: " + entity.isStreaming());
            String content = EntityUtils.toString(entity);
            System.out.println("content:" + content);
            Book book = JSON.parseObject(content, Book.class);
            System.out.println("============");
            System.out.println(book);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Book book = HttpClientUtil.doGet("https://api.douban.com/v2/book/isbn/978-7-302-22798-4",Book.class);
        System.out.println("book: " + book);
    }
}
